library(iml)
library(kknn)
library(shapviz)
library(xgboost) # 不再需要，但可以保留如果你打算比较模型
library(pROC)    # 不再需要，除非你打算做ROC曲线分析

setwd("D:/rCode/临床/临床论文/论文2") # 修改当前工作路径
demo <- read.csv("chb_and_hs.csv")     # 读取数据
dev <- demo[demo$type==1,]             # 筛选数据

# 创建KNN模型
knn_model <- kknn(hepatic_inflammation ~ ., 
                  data = dev, k = 5) 
knn_model <- with(dev, kknn(hepatic_inflammation ~ ., k = 5))
# 预测
pred <- predict(knn_model, newdata = dev)

# 创建解释器对象
explainer <- Explainer$new(knn_model, 
                           data = dev[, -which(names(dev) == "hepatic_inflammation")], 
                           y = dev$hepatic_inflammation)

# 计算SHAP值
shap_values <- shap(explainer)

# 特征重要性
sv_importance(shap_values)